package cn.syc.struck.demo.http;


import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.syc.struck.demo.App;
import cn.syc.struck.demo.http.entity.HttpResult;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by czz on 16/3/9.
 */
public abstract class HttpMethods {

    //public static final String BASE_URL = "https://api.douban.com/v2/movie/";
    //public static final String BASE_URL = "http://10.0.2.2:8080/api/";

    private static final int DEFAULT_TIMEOUT = 20;

    protected Retrofit retrofit;


    //构造方法私有
    protected HttpMethods() {

        String __url = App.getInstance().getPrefValue("setting.horst_url", "http://10.0.2.2:9999") + "/";

        retrofit = new Retrofit.Builder()
                //.client(builder.build())
                .client(genericClient())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //.baseUrl(BASE_URL)
                .baseUrl(__url)
                .build();
    }

    private OkHttpClient genericClient() {
        //手动创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        //显示Http返回日志
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(
                new HttpLoggingInterceptor.Logger() {
                    @Override
                    public void log(String message) {
                        System.out.println("OkHttp====:" + message);
                    }
                }
        );
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        builder.interceptors().add(logging);
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);

        builder.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //----------------
                Request originalRequest = chain.request();
                //if (Your.sToken == null || alreadyHasAuthorizationHeader(originalRequest)) {
                //    return chain.proceed(originalRequest);
                //}

                System.out.println("method=" + originalRequest.method());
                System.out.println("url=" + originalRequest.url());

                Request authorised = originalRequest.newBuilder()
                        .addHeader("User-Agent", App.getInstance().getUserAgent())
                        .addHeader("token", "aaaaaa")
                        .addHeader("sign", "bbbbbb")
                        .build();
                return chain.proceed(authorised);

            }
        }).build();

        return builder.build();

    }


    //================================

    protected <T> void toSubscribe(Observable<T> o, Subscriber<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
     */
    public class HttpResultFunc<T> implements Func1<HttpResult<T>, T> {

        @Override
        public T call(HttpResult<T> httpResult) {
            if (httpResult.getCode() != 200) {
                throw new ApiException(httpResult.getCode());
            }
            return httpResult.getDetail();
        }
    }

}
